<template>
  <div v-loading="loading" class="statement-mall-record app-main-content-box">
    <!-- 积分商城兑换明细 -->
    <app-main-title title="积分商城兑换明细" />
    <!-- 说明 -->
    <div class="app-main-tips-box top-tips">
      <div class="title">
        <i class="el-icon-warning" /> 报表说明
      </div>
      <ul>
        <li>1.本报表是积分兑换的所有记录，你可以通过筛选数据，得到自己对账或者数据分析所需的数据。</li>
        <li>2.本报表记录商城通过积分兑换商品的记录。</li>
      </ul>
    </div>

    <!-- 筛选 -->
    <div class="filter">
      <el-form ref="filterForm" :model="filterForm" label-width="100px" size="small">
        <el-form-item
          label="选择时间："
          prop="date"
          :rules="[
            { required: true, message: '时间区间不能为空'}
          ]"
        >
          <el-date-picker
            v-model="filterForm.date"
            type="datetimerange"
            range-separator="~"
            value-format="yyyy-MM-dd HH:mm"
            format="yyyy-MM-dd HH:mm"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>

        <!-- 筛选 -->
        <div class="app-main-filter-collapse-box">
          <el-collapse>
            <el-collapse-item ref="filterCollapse" title="按条件筛选" name="1">
              <!-- <el-form-item label="变动类型：" prop="sources">
                <el-checkbox
                  :indeterminate="isIndeterminateSources"
                  v-model="checkAllSources"
                  @change="handleCheckAllSourcesChange"
                  class="fl"
                >全选</el-checkbox>
                <el-checkbox-group
                  v-model="filterForm.sources"
                  @change="handleCheckBusinessTypeChange"
                >
                  <el-checkbox
                    :label="item"
                    v-for="(item,index) in sourcesOption"
                    :key="index"
                  >{{item}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>-->
              <el-form-item label="兑换类型：" prop="productType">
                <el-radio-group v-model="filterForm.productType">
                  <el-radio label="all">所有</el-radio>
                  <el-radio
                    v-for="(item,index) in productTypeOptions"
                    :key="index"
                    :label="index"
                  >{{ item }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
        </div>

        <el-form-item class="filter-btn">
          <el-button type="primary" round @click="submitForm('filterForm')">查 询</el-button>
          <el-button round @click="resetForm('filterForm')">重 置</el-button>
          <!-- <el-button v-if="!$store.getters.banBtnList.includes('BTN_POINTS_MALL_EXCHANGE_DETAIL_EXPORT')" round @click="downExcel">导 出</el-button> -->
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计卡片 start -->
    <div>
      <AppTableStatisticsCard :statistics-card-data="statisticsCardData" />
    </div>
    <!-- 统计卡片 end -->

    <!-- 列表 -->
    <div>
      <el-table :data="list" border style="width: 100%" empty-text="暂无数据">
        <el-table-column prop="createTime" label="兑换时间" fixed="left" />
        <el-table-column prop="orderNo" label="兑换单号" />
        <el-table-column prop="title" label="兑换内容" />
        <el-table-column prop="orderType" label="类型">
          <template slot-scope="scope">
            <span>{{ productTypeOptions[scope.row.orderType] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalPoint" label="积分消耗" />
        <el-table-column prop="customerName" label="兑换人">
          <template slot-scope="scope">
            <a
              href
              class="app-text-color-primary"
              @click.prevent="goVipDetail(scope.row.customerId)"
            >
              <u>{{ scope.row.customerName?scope.row.customerName:scope.row.customerId }}</u>
            </a>
          </template>
        </el-table-column>
        <el-table-column prop="memberCardName" label="卡类型" />
        <el-table-column prop="memberCardNo" label="卡号" />
        <el-table-column width="80" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="openDialogDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination-direction
        v-if="paginationConfig.total!==0"
        :config="paginationConfig"
        @sizeschange="sizesChange"
        @pagechange="pageChange"
      />
    </div>

    <!-- 弹框 -->
    <dialog-detail ref="dialogDetail" />
  </div>
</template>

<script>
import {
  getPointsMallRecordsList,
  getPointsMallRecordsDetail,
  getPointsMallListStats
} from '@/api/statement'
import DialogDetail from './components/DialogDetail'
export default {
  components: {
    DialogDetail
  },
  data() {
    return {
      // 配置
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      productTypeOptions: ['优惠券'],
      // 状态
      // checkAllSources: true, // sources 多选状态
      // isIndeterminateSources: false, // sources
      loading: false, // 表格loading
      // 数据
      statisticsCardData: [],
      list: [], // 表格数据
      filterForm: {
        date: [
          this.$momentMini().format('YYYY-MM-DD') + ' 00:00:00',
          this.$momentMini().format('YYYY-MM-DD') + ' 23:59:59'
        ], // 开始结束时间
        productType: 'all', // 商品类型
        source: 0 // 订单来源 商城
      }
    }
  },
  mounted() {
    this.fetchData()
    const arrFrom = ['invoice','cancelTable']
    this.$route.query.orderNo && arrFrom.indexOf(this.$route.query.from) > -1 && this.openDialogDetail({ orderNo: this.$route.query.orderNo })
  },
  methods: {
    /**
       * 获取数据
       */

    // 获取请求筛选数据
    setRequestParams() {
      const params = Object.assign({}, this.filterForm)
      params.beginTime = params.date[0]
      params.endTime = params.date[1]
      // 判断是否打开筛选
      if (!this.$refs.filterCollapse.isActive) {
        delete params.productType
      }
      delete params.date
      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }
      return params
    },

    // 获取记录数据
    fetchData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      this.$refs.filterForm.validate(valid => {
        if (valid) {
          const params = this.setRequestParams()
          params.pageNum = page
          params.pageSize = pageSize
          this.loading = true
          Promise.all([this.getList(params), this.getCount(params)]).then(
            res => {
              this.loading = false
            }
          )
        }
      })
    },

    // 获取列表
    getList(params) {
      return new Promise((resolve, reject) => {
        getPointsMallRecordsList(params)
          .then(res => {
            this.list = res.data.list
            this.paginationConfig.total = res.data.total
            this.paginationConfig.page = res.data.pageNum
          })
          .finally(() => {
            resolve()
          })
      })
    },

    // 获取统计
    getCount(params) {
      return new Promise((resolve, reject) => {
        if (params.pageNum !== 1) {
          resolve()
        } else {
          this.statisticsCardData = [
            {
              title: '累计消耗积分数 / 个',
              value: 0,
              describeList: [],
              detailList: []
            }
          ]
          getPointsMallListStats(params)
            .then(res => {
              this.statisticsCardData[0].value = res.data.totalPoint
                ? res.data.totalPoint
                : 0
            })
            .finally(() => {
              resolve()
            })
        }
      })
    },

    // 分页sizes改变
    sizesChange() {
      this.fetchData()
    },

    // 分页page改变
    pageChange() {
      this.fetchData()
    },

    /**
       * 按钮组
       */

    // 跳转会员详情
    goVipDetail(id) {
      this.$router.push({
        name: 'VipDetail',
        query: { customerId: id }
      })
    },

    // 打开详情
    openDialogDetail(row) {
      this.$refs.dialogDetail.open(row).then(res => {})
    },

    // 查询
    submitForm() {
      this.fetchData(1)
    },

    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.checkAllSources = true // sources 多选状态
      this.isIndeterminateSources = false // sources
    }

    /**
       * 状态
       */
    // checkAllSources多选状态
    // handleCheckAllSourcesChange(val) {
    //   if (val) {
    //     this.filterForm.sources = this.sourcesOption;
    //     this.checkAllSources = true;
    //   } else {
    //     this.filterForm.sources = [];
    //     this.checkAllSources = false;
    //   }
    //   this.isIndeterminateSources = false;
    // },

    // handleCheckBusinessTypeChange(value) {
    //   let checkedLength = value.length;
    //   let maxLength = this.sourcesOption.length;
    //   this.checkAllSources = checkedLength === maxLength;
    //   this.isIndeterminateSources =
    //     checkedLength > 0 && checkedLength < maxLength;
    // }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  /* 头部说明 */
  .top-tips {
    margin-bottom: 20px;
  }

  /* 筛选 */
  .filter {
    .filter-btn {
      margin-bottom: 20px;
    }
    /* 重置多选左边距 */
    .el-checkbox + .el-checkbox {
      margin-left: 0;
    }
    .el-checkbox {
      margin-right: 10px;
    }
  }
</style>
